import { View, Text, Image, Input, Button, Form } from '@tarojs/components';
import Taro from '@tarojs/taro';
import styles from './index.less';
import { useState } from 'react';
import { inject, observer } from 'mobx-react';
import type { UserStore } from '@/store/types';
import { uploadTempToOSS } from '@/services/oss-upload';

const defaultUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

const ProfileEdit = inject('userStore')(observer(({ userStore }: { userStore: UserStore }) => {
  const [nickname, setNickname] = useState('');
  const [avatarUrl, setAvatarUrl] = useState('');

  const handleAvatarChange = (e) => {
    if (e.detail.avatarUrl) {
      setAvatarUrl(e.detail.avatarUrl);
    }
  };

  const handleUploadAndRegister = async (nickname: string, avatarUrl: string) => {
    Taro.showLoading({
      title: '上传中...',
    });
    try {
      const ossUrl = await uploadTempToOSS(avatarUrl);
      await userStore.handleRegister({ nickname, avatarUrl: ossUrl });
      Taro.hideLoading();
    } catch (error) {
      Taro.showToast({
        title: '失败:' + error,
        icon: 'none',
      });
    }
  }

  const handleSubmit = () => {
    if (!nickname) {
      Taro.showToast({
        title: '请输入昵称',
        icon: 'none'
      });
      return;
    }
    console.log(nickname, avatarUrl);

    Taro.showModal({
      title: '提示',
      content: '确定保存吗？',
      success: async (res) => {
        if (res.confirm) {
          handleUploadAndRegister(nickname, avatarUrl)
        }
      }
    })

  };

  return (
    <View className={styles.container}>
      <Button
        className={styles.avatarWrapper}
        open-type='chooseAvatar'
        onChooseAvatar={handleAvatarChange}
      >
        <Image className={styles.avatar} src={avatarUrl || defaultUrl} />
      </Button>
      <View className={styles.inputWrapper}>
        <Text className={styles.inputTitle}>昵称</Text>
        <Input
          className={styles.nicknameInput}
          placeholder='请输入昵称'
          value={nickname}
          onInput={(e) => setNickname(e.detail.value)}
          type='nickname'
        />
      </View>



      <Button className={styles.submitButton} onClick={handleSubmit} formType='submit'>
        保存
      </Button>
    </View>
  );
}));

export default ProfileEdit; 